package com.siddy.bbs.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.InputFilter;
import android.text.LoginFilter.UsernameFilterGeneric;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.siddy.bbs.R;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link LoginFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link LoginFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class LoginFragment extends DialogFragment {

	public static final String ARG_PASSWORD = "arg_password";
	public static final String ARG_ACCOUNT = "arg_account";

	// TODO: Rename and change types of parameters
	private String mAccount;
	private String mPassword;

	// UI references.
	private EditText mAccountView;
	private EditText mPasswordView;

	private OnFragmentInteractionListener mListener;

	private boolean passwordError;

	/**
	 * Use this factory method to create a new instance of
	 * this fragment using the provided parameters.
	 *
	 * @param param1 Parameter 1.
	 * @param param2 Parameter 2.
	 * @return A new instance of fragment LoginFragment.
	 */
	// TODO: Rename and change types and number of parameters
	public static LoginFragment newInstance(Bundle auth) {
		LoginFragment fragment = new LoginFragment();
		if (auth != null)
			fragment.setArguments(auth);
		return fragment;
	}

	public LoginFragment() {
		// Required empty public constructor
	}

	public void setPasswordError(boolean error) {
		passwordError = error;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bd = getArguments();
		if (bd != null) {
			mAccount = bd.getString(ARG_ACCOUNT);
			mPassword = bd.getString(ARG_PASSWORD);
		}
		// setStyle(STYLE_NO_TITLE, 0);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_login, container, false);
		mAccountView = (EditText) v.findViewById(R.id.account);
		mAccountView.setFilters(new InputFilter[] { new UsernameFilterGeneric() });

		mPasswordView = (EditText) v.findViewById(R.id.password);
		if (mAccount != null) {
			mAccountView.setText(mAccount);
			mPasswordView.setText(mPassword);
		}
		mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
				if (id == R.id.login || id == EditorInfo.IME_NULL) {
					attemptLogin();
					return true;
				}
				return false;
			}
		});
		v.findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				attemptLogin();
			}
		});
		if (passwordError) {
			mPasswordView.setError(getString(R.string.error_incorrect_password));
			mPasswordView.requestFocus();
		}
		return v;
	}

	// TODO: Rename method, update argument and hook method into UI event
	public void onButtonPressed(Bundle bundle) {
		if (mListener != null) {
			mListener.onFragmentInteraction(bundle);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnFragmentInteractionListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
		}
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;
	}

	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated
	 * to the activity and potentially other fragments contained in that
	 * activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnFragmentInteractionListener {
		// TODO: Update argument type and name
		public void onFragmentInteraction(Bundle bundle);
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {

		if (mListener == null) {
			return;
		}

		// Reset errors.
		mAccountView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mAccount = mAccountView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mAccount)) {
			mAccountView.setError(getString(R.string.error_field_required));
			focusView = mAccountView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			Bundle bd = new Bundle();
			bd.putString(ARG_ACCOUNT, mAccount);
			bd.putString(ARG_PASSWORD, mPassword);
			onButtonPressed(bd);
		}
	}

}
